<template>
  <div>
    <!-- 筛选条件 -->
    <a-form layout="inline">
      <a-form-item label="所属区域">
        <a-space direction="vertical" size="large">
          <a-cascader :options="options" :style="{width:'320px'}" placeholder="Please select ..." />
        </a-space>
      </a-form-item>
      <a-form-item label="服务人员">
        <a-input v-model="filter.servicePerson" placeholder="工号/姓名/手机号" />
      </a-form-item>
      <a-form-item label="岗位">
        <a-select v-model="filter.position" placeholder="请选择岗位">
          <a-option :value="item.value" v-for="(item,index) in stationList" :key="index">{{item.label}}</a-option>
          <!-- 其他岗位选项 -->
        </a-select>
      </a-form-item>
      <a-form-item label="在职状态">
        <a-select v-model="filter.status" placeholder="请选择在职状态">
          <a-option :value="item" v-for="(item,index) in onJobList" :key="index">{{item}}</a-option>
          <!-- 其他状态选项 -->
        </a-select>
      </a-form-item>
      <a-form-item label="上单状态">
        <a-select v-model="filter.status" placeholder="请选择上单状态">
          <a-option :value="item" v-for="(item,index) in onJobList" :key="index">{{item}}</a-option>
          <!-- 其他状态选项 -->
        </a-select>
      </a-form-item>
      <a-form-item label="入职日期">
        <a-date-picker/>
      </a-form-item>
      <a-form-item label="人员类型">
        <a-select v-model="filter.userType" placeholder="请选择人员类型">
          <a-option :value="item" v-for="(item,index) in onJobList" :key="index">{{item}}</a-option>
          <!-- 其他状态选项 -->
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-button @click="handleReset">重置</a-button>
      </a-form-item>
    </a-form>

    <!-- 服务人员列表 -->
    <pro-table
      :columns="columns"
      :request="fetchServicePersonData"
      row-key="id"  
      :pagination="pagination"
      :action-ref="setActionRef"
      header-title="服务人员管理"
    >
      <template #option-render="{ dom }">
        <a-button key="primary" type="primary" @click="handleExport">导出</a-button>
        <a-button key="primary" type="primary" @click="showAddModal">新增人员</a-button>
      </template>
      <template #operation="{ column, record }">
        <template v-if="column.dataIndex === 'operation'">
          <a-button type="text" @click="handleDetail(record)">详情</a-button>
          <a-button type="text" @click="handleShowContent(record)">排班</a-button>
        </template>
      </template>
      <template #avatar="{ record }">
        <a-avatar>
          <img
            alt="avatar"
            :src="record.avatar"
          />
        </a-avatar>
      </template>
    </pro-table>

    <!-- 服务人员详情弹窗 -->
    <a-modal  v-model:visible="detailVisible" title="服务人员详情" width="800px">
      <a-card>
        <a-row class="grid-demo" :gutter="24">
          <a-col :span="12">
            <div>
              <a-avatar>
                <img
                  alt="avatar"
                  :src="detail.avatar"
                />
              </a-avatar>
            </div>
          </a-col>
          <a-col :span="12">
            <div></div>
          </a-col>
        </a-row>
      </a-card>
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" title="基本信息">
          <p>工号：{{ detail.id }}</p>
          <p>姓名：{{ detail.name }}</p>
          <p>性别：{{ detail.gender }}</p>
          <p>年龄：{{ detail.age }}</p>
          <p>手机号：{{ detail.phone }}</p>
          <p>居住地址：{{ detail.address }}</p>
          <p>紧急联系人：{{ detail.emergencyContact }}</p>
          <p>紧急联系人号码：{{ detail.emergencyContactPhone }}</p>
          <p>健康证有效期：{{ detail.healthCertificateValidity }}</p>
        </a-tab-pane>
        <a-tab-pane key="2" title="岗位信息">
          <p>岗位：{{ detail.position }}</p>
          <p>所属区域：{{ detail.region }}</p>
          <p>入职日期：{{ detail.entryDate }}</p>
          <p>人员类型：{{ detail.personType }}</p>
        </a-tab-pane>
        <a-tab-pane key="3" title="上单信息">
          <p>上单状态：{{ detail.orderStatus }}</p>
          <p>出行工具：{{ detail.travelTools }}</p>
          <p>接单距离：{{ detail.acceptRange }}</p>
          <p>接单时段：{{ detail.acceptStartTime }} - {{ detail.acceptEndTime }}</p>
          <p>接单范围：{{ detail.acceptRange }}</p>
        </a-tab-pane>
      </a-tabs>
    </a-modal>

    <!-- 新增人员弹窗 -->
    <a-modal v-model:visible="formVisible" :title="formTitle">
      <a-form ref="formRef" :model="formData" layout="vertical">
        <a-form-item label="姓名" :rules="[{ required: true, message: '请输入姓名' }]">
          <a-input v-model="formData.name" placeholder="请输入姓名" />
        </a-form-item>
        <a-form-item label="性别" :rules="[{ required: true, message: '请选择性别' }]">
          <a-select v-model="formData.sex" placeholder="请选择性别">
            <a-option value="1">男</a-option>
            <a-option value="2">女</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="出生日期" :rules="[{ required: true, message: '请输入出生日期' }]">
          <a-date-picker v-model="formData.birthday"/>
        </a-form-item>
        <a-form-item label="年龄" :rules="[{ required: true, message: '请输入年龄' }]">
          <a-input v-model="formData.title" placeholder="请输入年龄" />
        </a-form-item>
        <a-form-item label="身份证号" :rules="[{ required: true, message: '请输入身份证号' }]">
          <a-input v-model="formData.idCard" placeholder="请输入身份证号" />
        </a-form-item>
        <a-form-item label="手机号" :rules="[{ required: true, message: '请输入手机号' }]">
          <a-input v-model="formData.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="婚姻状况" :rules="[{ required: true, message: '请选择婚姻状况' }]">
          <a-select v-model="formData.type" placeholder="请选择婚姻状况">
            <a-option value="1">已婚</a-option>
            <a-option value="2">未婚</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="籍贯" :rules="[{ required: true, message: '请输入籍贯' }]">
          <a-input v-model="formData.nativePlace" placeholder="请输入籍贯" />
        </a-form-item>
        <a-form-item label="居住地" :rules="[{ required: true, message: '请输入居住地' }]">
          <a-input v-model="formData.address" placeholder="请输入居住地" />
        </a-form-item>
        <a-form-item label="紧急联系人" :rules="[{ required: true, message: '请输入紧急联系人' }]">
          <a-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
        </a-form-item>
        <a-form-item label="紧急联系人号码" :rules="[{ required: true, message: '请输入紧急联系人号码' }]">
          <a-input v-model="formData.emergencyContactPhone" placeholder="请输入紧急联系人号码" />
        </a-form-item>
        <a-form-item label="健康证有效期" :rules="[{ required: true, message: '请输入问卷标题' }]">
          <a-range-picker
              v-model="formData.dateRange"
              @change="onChange"
              @select="onSelect"
              style="width: 254px; marginBottom: 20px;"
            />          
            </a-form-item>
        <a-form-item label="选择小组" :rules="[{ required: true, message: '请选择选择小组' }]">
          <a-select v-model="formData.team" placeholder="请选择选择小组">
            <a-option value="xxx">xxx</a-option>
            <a-option value="xx">xx</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属区域" :rules="[{ required: true, message: '请选择所属区域' }]">
          <a-select v-model="formData.status" placeholder="请选择所属区域">
            <a-option value="启用">启用</a-option>
            <a-option value="禁用">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="出行工具" :rules="[{ required: true, message: '请选择出行工具' }]">
          <a-input v-model="formData.travelTools" placeholder="请输入出行工具" />
        </a-form-item>
        <a-form-item label="接单距离" :rules="[{ required: true, message: '请选择接单距离' }]">
          <a-input v-model="formData.acceptRange" placeholder="请输入接单距离" />
        </a-form-item>
        <a-form-item label="接单时段" :rules="[{ required: true, message: '请选择接单时段' }]">
          <a-range-picker></a-range-picker>
        </a-form-item>
        <a-form-item label="接单范围" :rules="[{ required: true, message: '请选择接单范围' }]">
          <a-input v-model="formData.acceptRange" placeholder="请输入接单范围" />
        </a-form-item>
        <a-form-item label="跟单地址" :rules="[{ required: true, message: '请选择跟单地址' }]">
          <a-input v-model="formData.title" placeholder="请输入跟单地址" />
        </a-form-item>

        <a-form-item label="身份证" field="image">
          <div v-if="formData.image">
            <a-image :src="formData.image" width="100" height="100" />
            <a-button type="text" @click="formData.image = ''">删除图片</a-button>
          </div>
          <div v-else>
            <a-upload
              action="https://fuwu-test.habitat.cn/service/system/upload"
              :show-file-list="false"
              :data="{ type: 1 }"
              @success="handleUploadSuccess"
            >
              <a-button type="primary">上传图片</a-button>
            </a-upload>
          </div>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="formVisible = false">取消</a-button>
        <a-button type="primary" @click="handleSubmit">提交</a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible="visible" width="90%">
      <CalendarComponent    ref="calendarRef"
      :events="events"
      :editable="true"
      :selectable="true"
      @dateClick="handleDateClick"
      @eventClick="handleEventClick"
      @select="handleSelect"></CalendarComponent>
    </a-modal>
  </div>
</template>
  
  <script lang="ts">
  import { defineComponent, ref, Ref } from 'vue';
import { getServicePersonList, saveServicePerson,getServicePerson } from '@/api/servicePerson'; // 假设你有一个获取服务人员数据的API
import CalendarComponent from '@/components/FullCalendar/indexl.vue'

export default defineComponent({
  name: 'servicePersonnel',
  components: { CalendarComponent },
  data() {
  },
  setup() {
    const formData = ref({
      id: null,
      userNo: "00001", // 编号
      name: "原朝", // 姓名
      sex: 1, // 性别 1男2女
      birthday: "1996-02-29", // 出生日期
      idCard: "14052119980090111", // 身份证号
      phone: "18801038095", // 手机号
      userType: "1", // 服务人员类型 1自营人员 2灵活用工
      productType: 1, // 服务产品类型 1保洁 2搬家 3保养 4维修
      maritalStatus: 1, // 婚姻状态 1已婚 2未婚
      workYear: 5, // 工作年限
      nativePlace: "山西", // 籍贯
      address: "山西太原", // 居住地
      emergencyContact: "原C", // 紧急联系人
      emergencyContactPhone: "18899009002", // 紧急联系人号码
      insuranceCategory: "商业保险", // 保险类别
      serviceGroupId: 1, // 所属小组ID
      insuranceStatus: "0", // 是否已投保 0是1否
      insuranceStartDate: "2023-09-09", // 保险有效期
      insuranceEndDate: "2024-09-09", // 保险有效期
      belongProvince: "北京市", // 所属省份
      belongCity: "北京", // 所属城市
      belongCounty: "丰台区", // 所属区县
      travelTools: "电动车", // 出行工具
      acceptStartTime: "09:00", // 接单时段-开始时间
      acceptEndTime: "20:00", // 接单时段-开始时间
      acceptRange: 20, // 接单范围km
      acceptCity: "1", // 接单城市
      acceptCounty: "2,3", // 接单区/县
      idCardFrontImage: "xxx.jpg", // 身份证正面图片
      idCardBackImage: "xxx1.jpg", // 身份证背面图片
      healthImage: "xxx12.jpg", // 健康证图片
      status: 0, // 状态0正常 1禁用
      dispatchHomeProvince: "", // 派单省份-家
      dispatchHomeCity: "", // 派单城市-家
      dispatchHomeCounty: "", // 派单区/县-家
      dispatchHomeAddress: "", // 派单详细地址-家
      dispatchCompanyProvince: "", // 派单省份-公司
      dispatchCompanyCity: "", // 派单城市-公司
      dispatchCompanyCounty: "", // 派单区/县-公司
      dispatchCompanyAddress: "" // 派单详细地址-公司
    });

    const handleUploadSuccess = (file, fileList) => {
      // 假设返回的数据在file.response中
      const response = file.response;
      if (response && response.success && response.data) {
        // 将返回的URL设置到表单的image字段
        console.log(response, formData)
        formData.image = response.data.url;
      }
    };

    const formVisible = ref(false);
    const formTitle = ref('新增人员');
    const onJobList = ['在职', '离职'] // 在职状态
    const stationList = [{ label: '自营人员', value: '1' }, { label: '灵活用工', value: '2' }]
    const options = [
      {
        value: 'beijing',
        label: 'Beijing',
        children: [
          {
            value: 'chaoyang',
            label: 'ChaoYang',
            children: [
              {
                value: 'datunli',
                label: 'Datunli',
              },
            ],
          },
          {
            value: 'haidian',
            label: 'Haidian',
          },
          {
            value: 'dongcheng',
            label: 'Dongcheng',
          },
          {
            value: 'xicheng',
            label: 'Xicheng',
            children: [
              {
                value: 'jinrongjie',
                label: 'Jinrongjie',
              },
              {
                value: 'tianqiao',
                label: 'Tianqiao',
              },
            ],
          },
        ],
      },
      {
        value: 'shanghai',
        label: 'Shanghai',
        children: [
          {
            value: 'huangpu',
            label: 'Huangpu',
          },
        ],
      },
    ];

    // 筛选条件
    const filter = ref({
      city: '',
      servicePerson: '',
      position: '',
      status: '',
    });

    // 表格列定义
    const columns = [
      { title: '头像', dataIndex: 'avatar', hideInSearch: true , slotName: 'avatar' },
      { title: '服务人员信息', dataIndex: 'name', hideInSearch: true },
      { title: '岗位信息', dataIndex: 'positionInfo', hideInSearch: true },
      { title: '所属区域', dataIndex: 'region', hideInSearch: true },
      { title: '居住地址', dataIndex: 'address', hideInSearch: true },
      { title: '入职日期', dataIndex: 'entryDate', hideInSearch: true },
      { title: '上单状态', dataIndex: 'status', hideInSearch: true, valueEnum:{
        0: {text: '正常'},
        1: {text: '禁用'}
      }},
      { title: '人员类型', dataIndex: 'userType', hideInSearch: true ,valueEnum:{
        1: {text: '自营人员'},
        2: {text: '灵活用工'}
      }},
      { title: '服务类型', dataIndex: 'productType', hideInSearch: true ,valueEnum:{
        1: {text: '保洁'},
        2: {text: '搬家'},
        3: {text: '保养'},
        4: {text: '维修'}
      }
},
      { title: '操作', dataIndex: 'operation', hideInSearch: true, slotName: "operation" },
    ];

    // 分页配置
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    // 服务人员详情
    const detailVisible = ref(false);
    const detail = ref({
      id: '',
      name: '',
      gender: '',
      age: '',
      phone: '',
      position: '',
      region: '',
      address: '',
      entryDate: '',
      orderStatus: '',
      personType: '',
      emergencyContact: '',
      emergencyContactPhone: '',
      healthCertificateValidity: '',
      travelTools: '',
      acceptStartTime: '',
      acceptEndTime: '',
      acceptRange: '',
    });
    const visible = ref(false);

    // 处理查询
    const handleSearch = () => {
      actionRef.value.reload();
    };
    const handleShowContent = () => {
      console.log('show content')
      visible.value = true
    }
    // 处理重置
    const handleReset = () => {
      filter.value = {
        city: '',
        servicePerson: '',
        position: '',
        status: '',
      };
      actionRef.value.reload();
    };

    // 处理详情查看
    const handleDetail = async (record) => {
      const data = await getServicePerson(record)
      detail.value = data;
      detailVisible.value = true;
    };

    // 获取服务人员数据
    const fetchServicePersonData = async (params: {
      current: number;
      pageSize: number;
    }) => {
      const data = {
        page: 1,
        size: 10,
        condition: {
          belongCity: "", // 所属市
          belongCounty: "", // 所属区
          name: "", // 工号/姓名/手机号
          // productType:"1",//服务产品类型 1保洁 2搬家 3保养 4维修
          // userType:"1"//服务人员类型 1自营人员 2灵活用工
        }
      }
      const response = await getServicePersonList({
        // ...params,
        // ...filter.value,
        ...data
      });
      console.log(response.list)
      pagination.value.total = response.total;
      return {
        data: response.list,
        success: true,
        total: response.total,
      };
    }; 
    const formRef = ref()
    // 设置actionRef
    const actionRef = ref();
    const setActionRef = (ref: Ref) => {
      actionRef.value = ref;
    };

    const handleExport = async () => {
      // exportFourType
      window.open('/service/demandFourType/downloadExcel', '_blank');
      // const response = await exportFourType('');
      // console.log(response, 'response')
      // const blob = new Blob([response.data], { type: 'application/octet-stream' });
      // const url = URL.createObjectURL(blob);
      // const link = document.createElement('a');
      // link.href = url;
      // link.download = 'four_types.csv';
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
      // URL.revokeObjectURL(url);
    };

    const showAddModal = () => {
      formVisible.value = true;
    };

    const handleSubmit = async () => {
      try {
        await formRef.value?.validate();
        await saveServicePerson(formData.value);
        formVisible.value = false;
        actionRef.value.reload();
      } catch (error) {
        console.error('表单校验失败', error);
      }
    };



    const events = ref([
      {
        title: '测试排班',
        start: '2024-11-15', 
        end: '2024-12-16',
        backgroundColor: '#409EFF'
      },
      {
        title: '测试事件2',
        start: '2024-11-20',
         end: '2024-12-25',
        allDay: true,
        backgroundColor: '#67C23A'
      }
    ])

    // 日历实例引用
    const calendarRef = ref(null)

    // 事件处理函数
    const handleDateClick = (arg) => {
      console.log('点击日期:', arg.dateStr)
    }

    const handleEventClick = (arg) => {
      console.log('点击事件:', arg.event.title)
    }

    const handleSelect = (arg) => {
      console.log('选择时间段:', arg.startStr, '至', arg.endStr)
    }

    return {
      events,
      calendarRef,
      handleDateClick,
      handleEventClick,
      handleSelect,
      filter,
      columns,
      pagination,
      detailVisible,
      detail,
      handleSearch,
      handleReset,
      handleDetail,
      fetchServicePersonData,
      setActionRef,
      options,
      onJobList,
      stationList,
      handleExport,
      formVisible,
      formTitle,
      formData,
      showAddModal,
      handleUploadSuccess,
      handleSubmit,
      formRef,
      visible,
      handleShowContent
    };
  },
});
</script>